import { useState, useEffect } from 'react';
import { message } from 'antd';

// 个人资料类型
interface ProfileData {
  username: string;
  email: string;
  avatar?: string;
  phone?: string;
  realName?: string;
  department?: string;
  position?: string;
  bio?: string;
}

// 密码修改类型
interface PasswordData {
  oldPassword: string;
  newPassword: string;
  confirmPassword: string;
}

// 安全设置类型
interface SecuritySettings {
  enableTwoFactor: boolean;
  loginNotification: boolean;
  sessionTimeout: number;
  allowedIPs: string;
}

// 通知设置类型
interface NotificationSettings {
  emailNotifications: boolean;
  smsNotifications: boolean;
  systemAlerts: boolean;
  securityAlerts: boolean;
  maintenanceNotifications: boolean;
  weeklyReports: boolean;
}

// 用户详情类型
interface UserDetails {
  id: string;
  username: string;
  email: string;
  avatar: string;
  phone: string;
  realName: string;
  department: string;
  position: string;
  bio: string;
  roles: string[];
  permissions: string[];
  createTime: string;
  lastLoginTime: string;
  loginCount: number;
  managedTenants?: number;
  resolvedTickets?: number;
  systemUptime?: string;
  managedUsers?: number;
  createdRoles?: number;
}

// 活动日志类型
interface ActivityLog {
  id: string;
  action: string;
  time: string;
  ip: string;
  device: string;
  status: 'success' | 'failed';
}

// 个人资料管理hook
export const useProfile = (isPlatformMode = false) => {
  const [profile, setProfile] = useState<UserDetails | null>(null);
  const [loading, setLoading] = useState(false);

  // 模拟用户数据
  const mockUser: UserDetails = isPlatformMode ? {
    id: '1',
    username: 'platform-admin',
    email: 'admin@v3cloud.com',
    avatar: '',
    phone: '13800138000',
    realName: '平台管理员',
    department: '技术部',
    position: '系统架构师',
    bio: '负责平台整体架构设计和技术管理',
    roles: ['platform_admin'],
    permissions: ['platform:*'],
    createTime: '2024-01-01 10:00:00',
    lastLoginTime: '2024-01-15 09:30:00',
    loginCount: 1247,
    managedTenants: 156,
    resolvedTickets: 89,
    systemUptime: '99.9%',
  } : {
    id: '1',
    username: 'admin',
    email: 'admin@example.com',
    avatar: '',
    phone: '13800138000',
    realName: '系统管理员',
    department: '技术部',
    position: '系统管理员',
    bio: '负责系统日常维护和用户管理',
    roles: ['admin'],
    permissions: ['user:read', 'user:write', 'role:read', 'role:write'],
    createTime: '2024-01-01 10:00:00',
    lastLoginTime: '2024-01-15 09:30:00',
    loginCount: 567,
    managedUsers: 89,
    createdRoles: 12,
  };

  const loadProfile = async () => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 500));
      setProfile(mockUser);
    } catch (error) {
      console.error('加载个人资料失败:', error);
      message.error('加载个人资料失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadProfile();
  }, [isPlatformMode]);

  return {
    profile,
    loading,
    refresh: loadProfile,
  };
};

// 个人资料操作hook
export const useProfileActions = () => {
  const [loading, setLoading] = useState(false);

  const updateProfile = async (data: ProfileData) => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 1000));
      message.success('个人资料更新成功');
    } catch (error) {
      message.error('更新失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const changePassword = async (data: PasswordData) => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 1000));
      message.success('密码修改成功');
    } catch (error) {
      message.error('密码修改失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const updateSecuritySettings = async (data: SecuritySettings) => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 1000));
      message.success('安全设置更新成功');
    } catch (error) {
      message.error('更新失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const updateNotificationSettings = async (data: NotificationSettings) => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 1000));
      message.success('通知设置更新成功');
    } catch (error) {
      message.error('更新失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const uploadAvatar = async (file: File) => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 1000));
      const mockUrl = URL.createObjectURL(file);
      message.success('头像上传成功');
      return mockUrl;
    } catch (error) {
      message.error('头像上传失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  return {
    loading,
    updateProfile,
    changePassword,
    updateSecuritySettings,
    updateNotificationSettings,
    uploadAvatar,
  };
};

// 安全设置管理hook
export const useSecuritySettings = () => {
  const [settings, setSettings] = useState<SecuritySettings>({
    enableTwoFactor: false,
    loginNotification: true,
    sessionTimeout: 30,
    allowedIPs: '',
  });
  const [loading, setLoading] = useState(false);

  const loadSettings = async () => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 300));
      // 模拟加载设置
    } catch (error) {
      console.error('加载安全设置失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadSettings();
  }, []);

  return {
    settings,
    loading,
    setSettings,
    refresh: loadSettings,
  };
};

// 通知设置管理hook
export const useNotificationSettings = (isPlatformMode = false) => {
  const [settings, setSettings] = useState<NotificationSettings>({
    emailNotifications: true,
    smsNotifications: false,
    systemAlerts: true,
    securityAlerts: true,
    maintenanceNotifications: true,
    weeklyReports: isPlatformMode,
  });
  const [loading, setLoading] = useState(false);

  const loadSettings = async () => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 300));
      // 模拟加载设置
    } catch (error) {
      console.error('加载通知设置失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadSettings();
  }, []);

  return {
    settings,
    loading,
    setSettings,
    refresh: loadSettings,
  };
};

// 活动日志hook
export const useActivityLogs = (isPlatformMode = false) => {
  const [logs, setLogs] = useState<ActivityLog[]>([]);
  const [loading, setLoading] = useState(false);

  const mockLogs: ActivityLog[] = [
    {
      id: '1',
      action: '登录系统',
      time: '2024-01-15 09:30:00',
      ip: '192.168.1.100',
      device: 'Chrome 120.0 on macOS',
      status: 'success',
    },
    {
      id: '2',
      action: isPlatformMode ? '创建租户' : '创建用户',
      time: '2024-01-15 09:25:00',
      ip: '192.168.1.100',
      device: 'Chrome 120.0 on macOS',
      status: 'success',
    },
    {
      id: '3',
      action: '修改个人资料',
      time: '2024-01-14 16:45:00',
      ip: '192.168.1.100',
      device: 'Chrome 120.0 on macOS',
      status: 'success',
    },
    {
      id: '4',
      action: '密码修改',
      time: '2024-01-14 16:30:00',
      ip: '192.168.1.100',
      device: 'Chrome 120.0 on macOS',
      status: 'success',
    },
    {
      id: '5',
      action: '登录失败',
      time: '2024-01-14 08:15:00',
      ip: '203.0.113.1',
      device: 'Unknown',
      status: 'failed',
    },
  ];

  const loadLogs = async () => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 500));
      setLogs(mockLogs);
    } catch (error) {
      console.error('加载活动日志失败:', error);
      message.error('加载活动日志失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadLogs();
  }, [isPlatformMode]);

  return {
    logs,
    loading,
    refresh: loadLogs,
  };
};

// 导出类型
export type {
  ProfileData,
  PasswordData,
  SecuritySettings,
  NotificationSettings,
  UserDetails,
  ActivityLog,
}; 